package edu.szu.huhanpeng.doodlingFight.view 
{
	import edu.szu.huhanpeng.doodlingFight.globalConst.GlobalConst;
	import edu.szu.huhanpeng.doodlingFight.interfaces.IChessData;
	import edu.szu.huhanpeng.doodlingFight.interfaces.IChessMediator;
	import edu.szu.huhanpeng.doodlingFight.model.ChessBoardProxy;
	import edu.szu.huhanpeng.doodlingFight.model.GameProxy;
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.interfaces.INotifier;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	/**
	 * ...
	 * @author Huhanpeng
	 */
	public class SelectorMediator extends Mediator implements IMediator, INotifier 
	{
		public static const NAME:String = "SelectorMediator";
		
		private var chessBoardProxy:ChessBoardProxy;
		
		private var chessAData:IChessData;
		
		private var chessBData:IChessData;
		
		public function SelectorMediator() 
		{
			super(NAME);
		}
		
		override public function listNotificationInterests():Array 
		{
			return [GlobalConst.noteName.CLICK_CHESS
					];
		}
		
		override public function handleNotification(note:INotification):void 
		{
			super.handleNotification( note );
			
			switch( note.getName() ) 
			{
				case GlobalConst.noteName.CLICK_CHESS:
					
					var chessName:String = note.getBody() as String;
					var chessClicked:IChessData = facade.retrieveProxy(chessName).getData() as IChessData;
					
					if (chessAData == null) 
					{
						chessAData = chessClicked;
						
					}
					else if (chessAData.name == chessName) 
					{
						chessAData = null;
					}
					//正确选择两个棋子，清除数据，通知检查是否成功
					else if (chessBData == null && isNearby(chessAData, chessClicked)) 
					{
						chessBData = chessClicked;
						
						
						sendNotification( chessAData.name.concat(ChessMediator.DIS_SELECT) );
						sendNotification( chessBData.name.concat(ChessMediator.DIS_SELECT) );
						
						sendNotification(GlobalConst.noteName.TRY_TO_CHANGE, new <IChessData>[chessAData, chessBData]);
						chessAData = chessBData = null;
					}
					else
					{
						sendNotification( chessAData.name.concat(ChessMediator.DIS_SELECT) );
						chessAData = chessClicked;
						chessBData = null;
					}
				break;
				
				default:
			}
		}
		
		private function isNearby(chessA:IChessData, chessClicked:IChessData):Boolean 
		{
			if (chessBoardProxy == null) 
			{
				chessBoardProxy = facade.retrieveProxy(ChessBoardProxy.NAME) as ChessBoardProxy;
			}
			
			var i:int = Math.abs(chessA.square.index - chessClicked.square.index);
			if (i == 1 || i == chessBoardProxy.size) 
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
	}

}